package com.xuxin.baby.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.xuxin.baby.R;
import com.xuxin.baby.base.BaseActivity;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.bean.BaseBean;
import com.xuxin.baby.bean.UploadFilesBean;
import com.xuxin.baby.bean.UserDataBean;
import com.xuxin.baby.contract.UploadFilesContract;
import com.xuxin.baby.contract.UserContract;
import com.xuxin.baby.event.UserFragmentEvent;
import com.xuxin.baby.glide.GlideApp;
import com.xuxin.baby.network.Retrofit;
import com.xuxin.baby.photo.PhotoUtils;
import com.xuxin.baby.popup.CityPopup;
import com.xuxin.baby.presenter.UploadFilesPresenter;
import com.xuxin.baby.presenter.UserPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.BaseUtils;
import com.xuxin.baby.utils.DatePickerUtils;
import com.xuxin.baby.utils.PathUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by xu_xin
 * Created on 2020.08.11 0011
 * 个人信息
 */
public class UserDataActivity extends BaseActivity implements UserContract.View, UploadFilesContract.View {
    private final UserContract.Presenter presenter = new UserPresenter(this);
    private final UploadFilesContract.Presenter presenter2 = new UploadFilesPresenter(this);
    RequestOptions options = RequestOptions.bitmapTransform(new CircleCrop());
    private final String[] nationList = new String[]{"汉族", "阿昌族", "鄂温克族", "傈僳族",
            "水族", "白族", "高山族", "珞巴族", "塔吉克族", "保安族", "仡佬族", "满族", "塔塔尔族", "布朗族",
            "哈尼族", "毛南族", "土家族", "布依族", "哈萨克族", "门巴族", "土族", "朝鲜族", "蒙古族", "佤族",
            "达斡尔族", "赫哲族", "苗族", "维吾尔族", "傣族", "回族", "仫佬族", "乌孜别克族", "德昂族", "基诺族",
            "纳西族", "锡伯族", "东乡族", "京族", "怒族", "瑶族", "侗族", "景颇族", "普米族", "彝族", "独龙族",
            "柯尔克孜族", "羌族", "裕固族", "俄罗斯族", "拉祜族", "撒拉族", "藏族", "鄂伦春族", "黎族", "畲族",
            "壮族", "其它"};
    @BindView(R.id.title_left)
    ImageView title_left;
    @BindView(R.id.title_right)
    ImageView title_right;
    @BindView(R.id.title_name)
    TextView title_name;
    @BindView(R.id.view_line)
    ImageView view_line;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.user_data_image)
    ImageView user_data_image;
    @BindView(R.id.user_data_nick)
    EditText user_data_nick;
    @BindView(R.id.user_data_birthday)
    TextView user_data_birthday;
    @BindView(R.id.user_data_nation)
    TextView user_data_nation;
    @BindView(R.id.user_data_role)
    TextView user_data_role;
    @BindView(R.id.user_data_birthAddress)
    TextView user_data_birthAddress;
    @BindView(R.id.user_data_address)
    TextView user_data_address;
    @BindView(R.id.user_data_grade)
    TextView user_data_grade;
    @BindView(R.id.user_data_score)
    TextView user_data_score;
    @BindView(R.id.user_data_grade_update)
    LinearLayout user_data_grade_update;
    @BindView(R.id.user_data_score_update)
    LinearLayout user_data_score_update;

    private String memberId;//用户id
    private String tenantId;//租户id
    private String token;//授权token
    private boolean loginGuide;
    private String nickName;
    private String birthday;
    private String nation;
    private String role;
    private String birthAddress;
    private String address;
    private String headImage;

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_user_data);
    }

    @Override
    public void initView() {
        title_name.setText("个人信息");
        button.setText("保存");
        Intent intent = getIntent();
        loginGuide = intent.getBooleanExtra("loginGuide", false);
        role = intent.getStringExtra("role");
        if (loginGuide) {
            title_name.setText("完善个人信息");
            title_left.setVisibility(View.INVISIBLE);
            view_line.setVisibility(View.INVISIBLE);
            user_data_grade_update.setVisibility(View.GONE);
            user_data_score_update.setVisibility(View.GONE);
        } else {
            title_name.setText("个人信息");
        }
    }

    @Override
    public void initData() {
        ACache aCache = ACache.get(this);
        memberId = aCache.getAsString(BaseConstant.memberId);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        handler.sendEmptyMessage(0);
    }

    @Override
    public void onComplete() {
        dismiss();
    }

    @Override
    @OnClick({R.id.title_left, R.id.user_data_image,
            R.id.user_data_birthday, R.id.user_data_nation,
            R.id.user_data_role, R.id.user_data_birthAddress,
            R.id.user_data_address, R.id.button})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.title_left) {
            finish();
        } else if (id == R.id.user_data_image) {
            PhotoUtils.openPhoto(this, new PhotoUtils.OnResultListener() {
                @Override
                public void onResult(List<LocalMedia> result) {
                    popup.setTitle("正在上传头像").show();
                    takePhoto(result);
                }
            });
        } else if (id == R.id.user_data_birthday) {
            DatePickerUtils.showDate(this, new DatePickerUtils.onListener() {
                @Override
                public void onShow(String time) {
                    user_data_birthday.setText(time);
                }
            });
        } else if (id == R.id.user_data_nation) {
            new XPopup.Builder(context)
                    .maxHeight(ScreenUtils.getScreenWidth())
                    .maxWidth((int) (ScreenUtils.getScreenWidth() * 0.8))
                    .asCenterList("请选择民族", nationList, new OnSelectListener() {
                        @Override
                        public void onSelect(int position, String text) {
                            user_data_nation.setText(text);
                        }
                    }).show();
        } else if (id == R.id.user_data_role) {
           /* new XPopup.Builder(context)
                    .isDestroyOnDismiss(true)
                    .asCenterList("请选择角色", new String[]{"爸爸", "妈妈"}, new OnSelectListener() {
                        @Override
                        public void onSelect(int position, String text) {
                            user_data_role.setText(text);
                        }
                    }).show();*/
        } else if (id == R.id.user_data_birthAddress) {
            new XPopup.Builder(context)
                    .dismissOnTouchOutside(true)
                    .asCustom(new CityPopup(context, new CityPopup.OnClickListener() {
                        @Override
                        public void onCity(String city) {
                            user_data_birthAddress.setText(city);
                        }
                    }))
                    .show();
        } else if (id == R.id.user_data_address) {
            new XPopup.Builder(context)
                    .dismissOnTouchOutside(true)
                    .asCustom(new CityPopup(context, new CityPopup.OnClickListener() {
                        @Override
                        public void onCity(String city) {
                            user_data_address.setText(city);
                        }
                    }))
                    .show();
        } else if (id == R.id.button) {
            nickName = user_data_nick.getText().toString();
            birthday = user_data_birthday.getText().toString();
            nation = user_data_nation.getText().toString();
            role = user_data_role.getText().toString();
            birthAddress = user_data_birthAddress.getText().toString();
            address = user_data_address.getText().toString();
            if (null == userDataBean || null == userDataBean.getResult()) {
                ToastUtils.showShort("用户信息获取失败");
            } else if (StringUtils.isEmpty(nickName)) {
                ToastUtils.showShort("请填写昵称");
            } else {
                try {
                    popup.setTitle("正在更新").show();
                    handler.sendEmptyMessage(10);
                } catch (Exception e) {
                    e.printStackTrace();
                    dismiss();
                }
            }
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 0://个人信息
                    presenter.getUserData(tenantId, token, memberId);
                    break;
                case 1://图片上传
                    presenter2.uploadFiles(tenantId, token, memberId, "Members", "avatar", parts);
                    break;
                case 2:
                    presenter.uploadAvatar(tenantId, token, memberId, (String) msg.obj);
                    break;
                case 10:
                    presenter.updateUserData(tenantId, token, memberId,
                            userDataBean.getResult().getMobile(), userDataBean.getResult().getAvatar()
                            , nickName, birthday, nation, role, birthAddress, address);
                    break;
            }
            return false;
        }
    });

    private UserDataBean userDataBean;

    @Override
    public void onSuccess(UserDataBean userDataBean) {
        this.userDataBean = userDataBean;
        this.headImage = userDataBean.getResult().getAvatar();
        if (!StringUtils.isEmpty(userDataBean.getResult().getNickname())) {
            user_data_nick.setText(userDataBean.getResult().getNickname());
        } else {
            String defaultNick = "用户" + userDataBean.getResult().getId();
            user_data_nick.setText(defaultNick);
        }
        user_data_birthday.setText(BaseUtils.getTime(userDataBean.getResult().getBirthday()));
        user_data_nation.setText(userDataBean.getResult().getEthnicity());
        if (loginGuide) {
            user_data_role.setText(role);
        } else {
            user_data_role.setText(userDataBean.getResult().getRole());
        }
        user_data_birthAddress.setText(userDataBean.getResult().getBirthAddress());
        user_data_address.setText(userDataBean.getResult().getAddress());
        user_data_grade.setText(userDataBean.getResult().getGrade());
        user_data_score.setText(userDataBean.getResult().getPoints());
        String headImage = Retrofit.image_url + userDataBean.getResult().getAvatar();
        LogUtils.e("个人信息_image = " + headImage);
        GlideApp.with(context).load(headImage).apply(options).placeholder(R.mipmap.img_placeholder_head).into(user_data_image);
    }

    @Override
    public void onImageSuccess(BaseBean baseBean) {
        EventBus.getDefault().post(new UserFragmentEvent());
        ToastUtils.showShort("头像上传成功");
        handler.sendEmptyMessage(0);
    }

    @Override
    public void onSuccess(BaseBean baseBean) {
        if (loginGuide) {
            Bundle bundle = new Bundle();
            bundle.putString("role", role);
            bundle.putString("roleName", nickName);
            bundle.putString("roleImage", headImage);
            ActivityUtils.startActivity(bundle, LoginGuide1Activity.class);
        }
        finish();
    }

    @Override
    public void onSuccess(UploadFilesBean uploadFilesBean) {
        this.headImage = uploadFilesBean.getResult();
        Message message = Message.obtain();
        message.what = 2;
        message.obj = uploadFilesBean.getResult();
        handler.sendMessage(message);
    }

    private List<MultipartBody.Part> parts;

    public void takePhoto(List<LocalMedia> result) {
        LocalMedia media = result.get(0);
        String path = media.isCompressed() ? media.getCompressPath() : media.getPath();
        LogUtils.e("path = " + path);
        try {
            LogUtils.e("加载");
            GlideApp.with(context).load(path).apply(options).into(user_data_image);
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("加载失败");
        }
        File file = new File(path);
        RequestBody requestBody = RequestBody.create(file, MediaType.parse("image/jpeg"));
        parts = new ArrayList<>();
        parts.add(MultipartBody.Part.createFormData("files", PathUtils.getImageName(), requestBody));
        handler.sendEmptyMessage(1);
    }
}